package com.personal.web.shopadmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.personal.dto.ImageHolder;
import com.personal.dto.ShopExecution;
import com.personal.entity.Area;
import com.personal.entity.PersonInfo;
import com.personal.entity.Shop;
import com.personal.entity.ShopCategory;
import com.personal.enums.ShopStateEnum;
import com.personal.service.AreaService;
import com.personal.service.ShopCategoryService;
import com.personal.service.ShopService;
import com.personal.utils.HttpServletRequestUtil;
import com.personal.utils.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 萌新
 * @version 1.0
 * @date 2021/4/14 10:43
 */

@Controller
@RequestMapping("/shopadmin")
public class ShopController {

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopCategoryService shopCategoryService;

    @Autowired
    private AreaService areaService;

    /**
     * 从商铺列表页面中，点击“进入”按钮进入
     * 某个商铺的管理页面的时候，对session中的数据的校验从而进行页面的跳转，是否跳转到店铺列表页面或者可以直接操作该页面
     * 访问形式如下
     * 	    http://ip:port/o2o/shopadmin/shopmanagement?shopId=xxx
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getshopmanageinfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getShopMangementInfo(HttpServletRequest request){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //获取shopId
        long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        //如果shopId不合法
        if (shopId <= 0){
            //尝试从session中获取
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if (currentShopObj == null){
                //如果session中也没有shop信息，告诉view层 重定向
                modelMap.put("redirect",true);
                modelMap.put("url","/shopadmin/shoplist");
            }else {
                //告诉view层  进入该页面
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId", currentShop.getShopId());
            }
        }else {
            //shopId合法的话
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            //将currentShop放到session中去
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
        }
        return modelMap;
    }


    /**
     * 获取店铺列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/getshoplist",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getShopList(HttpServletRequest request){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        PersonInfo user = new PersonInfo();
        user.setUserId(1L);
        user.setName("test");
        request.getSession().setAttribute("user",user);
        user = (PersonInfo) request.getSession().getAttribute("user");

        try {
            Shop shopCondition = new Shop();
            shopCondition.setOwner(user);
            ShopExecution se = shopService.getShopList(shopCondition,0,100);
            modelMap.put("shopList",se.getShopList());
            modelMap.put("user",user);
            modelMap.put("success",true);
        }catch (Exception e){
            modelMap.put("success", false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;
    }


    /**
     * 通过id查询店铺
     * @param request
     * @return
     */
    @RequestMapping(value = "/getshopbyid",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getShopById(HttpServletRequest request){
        Map<String, Object> modelMap = new HashMap<String,Object>();
        //这里的shopId是前端传过来的值
        Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if (shopId > -1){
            try {
                Shop shop = shopService.getByShopId(shopId);
                //获取区域列表
                List<Area> areaList = areaService.getAreaList();
                modelMap.put("shop",shop);
                modelMap.put("areaList",areaList);
                modelMap.put("success",true);
            }catch (Exception e){
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
            }
            //如果传入值失败的
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","empty shopId");
        }

       return modelMap;
    }


    /**
     * 因为是接收前端的请求，而前端的信息都封装在HttpServletRequest中，
     * 所以需要解析HttpServletRequest，获取必要的参数
     * 1. 接收并转换相应的参数，包括shop信息和图片信息 2. 注册店铺 3. 返回结果给前台
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/registershop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        // 0. 验证码校验
        if (!VerifyCodeUtil.verifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "验证码不正确");
            return modelMap;
        }

        // 1. 接收并转换相应的参数，包括shop信息和图片信息

        // 1.1 shop信息

        // shopStr 是和前端约定好的参数值，后端从request中获取request这个值来获取shop的信息
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        // 使用jackson-databind 将json转换为pojo
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            // 将json转换为pojo
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            e.printStackTrace();
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }

        // 1.2 图片信息 基于Apache Commons FileUpload的文件上传

        // Spring MVC中的 图片存在CommonsMultipartFile中
        CommonsMultipartFile shopImg = null;
        // 从request的本次会话中的上线文中获取图片的相关内容
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // shopImg是和前端约定好的变量名
            shopImg = (CommonsMultipartFile) multipartRequest.getFile("shopImg");
        } else {
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", "图片不能为空");
            return modelMap;
        }

        // 2. 注册店铺
        if (shop != null && shopImg != null) {
            // Session TODO
            // 店主persionInfo的信息，肯定要登录才能注册店铺。
            // 所以这部分信息我们从session中获取，尽量不依赖前端,这里暂时时不具备条件，后续改造，先硬编码，方便单元测试
            PersonInfo personInfo = (PersonInfo) request.getSession().getAttribute("user");
            shop.setOwner(personInfo);
            // 注册店铺

            // se = shopService.addShop(shop, shopImg); 改造前的调用方式
            // 这个时候，我们从前端获取到的shopImg是CommonsMultipartFile类型的，如何将CommonsMultipartFile转换为file.
            // 网上也有将CommonsMultipartFile转换为File的方法，并通过maxInMemorySize的设置尽量不产生临时文件
            // 这里我们换个思路,因为CommonsMultipartFile可以获取InputStream,Thumbnailator又可以直接处理输入流
            // 因为InputStream中我们无法得到文件的名称，而thumbnail中需要根据文件名来获取扩展名，所以还要再加一个参数String类型的fileName
            // 既然第二个和第三个参数都是通过shopImg获取的，为什么不直接传入一个shopImg呢？
            // 主要是为了service层单元测测试的方便，因为service层很难实例化出一个CommonsMultipartFile类型的实例
            ShopExecution se = null;

            try {
                ImageHolder imageHolder = new ImageHolder(shopImg.getInputStream(),shopImg.getOriginalFilename());
                se = shopService.addShop(shop, imageHolder);
                if (se.getState() == ShopStateEnum.CHECK.getState()) {
                    modelMap.put("success", true);
                    modelMap.put("errMsg", "注册成功");
                    //该用户可以操作的店铺列表
                    List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
                    if (shopList == null || shopList.size() == 0){
                        //如果是第一次创建店铺
                        shopList = new ArrayList<Shop>();
                    }
                    shopList.add(se.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", se.getStateInfo());
                }
            } catch (IOException e) {
                e.printStackTrace();
                modelMap.put("success", false);
                modelMap.put("errMsg", "addShop Error");
            }
        } else {
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺信息");
        }
        return modelMap;
    }

    @RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> modifyshop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();

        // 0. 验证码校验
        if (!VerifyCodeUtil.verifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "验证码不正确");
            return modelMap;
        }
        // 1. 接收并转换相应的参数，包括shop信息和图片信息

        // 1.1 shop信息

        // shopStr 是和前端约定好的参数值，后端从request中获取request这个值来获取shop的信息
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        // 使用jackson-databind 将json转换为pojo
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            // 将json转换为pojo
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            e.printStackTrace();
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
            return modelMap;
        }

        // 1.2 图片信息 基于Apache Commons FileUpload的文件上传 （ 修改商铺信息 图片可以不更新）

        // Spring MVC中的 图片存在CommonsMultipartFile中
        CommonsMultipartFile shopImg = null;
        // 从request的本次会话中的上线文中获取图片的相关内容
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // shopImg是和前端约定好的变量名
            shopImg = (CommonsMultipartFile) multipartRequest.getFile("shopImg");
        }

        // 2. 修改店铺
        if (shop != null && shop.getShopId() != null) {
            // Session 部分的 PersonInfo 修改商铺是不需要的设置的。
            // 修改店铺
            ShopExecution se = null;
            try {
                if (shopImg != null) {
                    ImageHolder imageHolder = new ImageHolder(shopImg.getInputStream(),shopImg.getOriginalFilename());
                    se = shopService.modifyShop(shop, imageHolder);
                } else {
                    se = shopService.modifyShop(shop, null);
                }
                // 成功
                if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
                    modelMap.put("success", true);
                    modelMap.put("errMsg", "修改成功");
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", se.getStateInfo());
                }
            } catch (Exception e) {
                e.printStackTrace();
                modelMap.put("success", false);
                modelMap.put("errMsg", "ModifyShop Error");
            }
        } else {
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", "ShopId不合法");
        }
        return modelMap;
    }


    @RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getshopinitinfo() {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<ShopCategory> shopCategoryList = null;
        List<Area> areaList = null;
        try {
            shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
            areaList = areaService.getAreaList();
            // 返回success shopCategoryList  areaList,前端通过 data.success来判断从而展示shopCategoryList和areaList的数据
            modelMap.put("success", true);
            modelMap.put("shopCategoryList", shopCategoryList);
            modelMap.put("areaList", areaList);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;
    }

}
